package cn.weakup.thread.interrupt;

import java.util.concurrent.TimeUnit;

/**
 * @author Dawn
 * @version 1.0.0
 * @desc
 * @date 2022/5/6
 */
public class ThreadInterruptTest {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                if(i == 2) {
                    // interrupted()方法会返回当前线程的中断标志位，【同时会重置中断标志位】
                    System.err.println("调用Thread.interrupted()，返回当前线程的中断标志位,同时会重置中断标志位");
                    Thread.interrupted();
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName()+" 依旧在运行" + i);
            }
        });
        thread.start();
        thread.start();

        Thread mainThread = Thread.currentThread();
        System.out.println("main线程isInterrupted状态：" + mainThread.isInterrupted());

        // thread.isInterrupted()方法会返回线程的中断标志位。
        System.out.println("线程启动后isInterrupted状态：" + thread.isInterrupted());

        // 执行线程的interrupt()方法,修改线程中断标志状态为true
        thread.interrupt();

        // 再次查看thread的中断标志状态
        System.out.println("线程调用interrupt()方法后isInterrupted状态：" + thread.isInterrupted());

        // 再次调用中断方法
        thread.interrupt();
        // 再次查看thread的中断标志状态
        System.out.println("线程再次调用中断方法interrupt()方法后isInterrupted状态：" + thread.isInterrupted());

        TimeUnit.SECONDS.sleep(3);
        System.out.println("线程调用interrupted()方法后isInterrupted状态：" + thread.isInterrupted());
        System.out.println("main线程isInterrupted状态：" + mainThread.isInterrupted());
    }
}
